// 1. 安装路由模块
// yarn add vue-router

// 2. 导入模块
import Vue from 'vue'

import VueRouter from 'vue-router'
import { getToken } from '../utils/localData'

// 3. 注册路由组件  <routet-view> <router-link> 
Vue.use(VueRouter)

// 4. 路由映射关系
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import User from '../views/User.vue'
import UserEdit from '../views/UserEdit.vue'
import Home from '../views/Home.vue'
import Article from '../views/Article.vue'
import UserFollow from '../views/UserFollow.vue'
import UserStar from '../views/UserStar.vue'
import UserComment from '../views/UserComment.vue'
import Comment from '../views/Comment.vue'
import Category from '../views/Category.vue'
import Search from '../views/Search.vue'
const routes = [
    { path: '/', redirect: '/home' },
    { path: '/home', component: Home },
    { path: '/login', component: Login, name: 'Login' },
    { path: '/register', component: Register },
    { path: '/article/:id', component: Article },
    { path: '/comment/:id', component: Comment },
    { path: '/category', component: Category },
    { path: '/search', component: Search },
    //  🧐直接在配置路由信息的时候，协商需要检查哪些页面
    { meta: { check: true }, path: '/user', component: User },
    { meta: { check: true }, path: '/user_edit', component: UserEdit },
    { meta: { check: true }, path: '/user_follow', component: UserFollow },
    { meta: { check: true }, path: '/user_star', component: UserStar },
    { meta: { check: true }, path: '/user_comment', component: UserComment },
]

// 5. new 一个路由实例
const router = new VueRouter({
    routes,
    mode: 'history'
})
// 路由守卫 - 就是一个路由跳转前自动执行的函数
// to 目标路由对象地址(去哪里)
// from 跳转前路由对象地址(从哪里来)  一般不用
// next next是否放行(是一个函数)
router.beforeEach((to, from, next) => {
    //  在这个数据范围内的路径，都要进行登录校验
    // let pathArr = ['/user', '/user_edit']
    // 部分页面访问的时候需要确认是否有token
    if (to.meta.check) {
        console.log(to.path, '需要检查的页面');
        // 如果有成功获取到token
        if (getToken()) {
            // 放行
            next()
        } else {
            // 没有token 就跳转到登录页
            next({ path: '/login' })
        }
    } else {
        // 普通页面，直接放行
        next()
    }
})

// 6.1  导出路由实例
export default router